import { domain } from './config/var'

const baseURL: string = `${domain}/App1`

/**
 * Tp依靠一个头判定ajax请求
 */
const ajaxHeader = new Headers({
  'x-requested-with': 'XMLHttpRequest'
})

let ppid: number

const getPPID = async (): Promise<Number> => {
  if (sessionStorage.getItem('ppid')) {
    ppid = parseInt(`${sessionStorage.getItem('ppid')}`)
    return ppid
  }
  const request = await fetch(`${baseURL}/Shop/getPPID`)
  const json = await request.json()
  if (json.status === '1') {
    ppid = parseInt(`${json.data.ppid}`)
    sessionStorage.setItem('ppid', `${ppid}`)
    return ppid
  } else {
    throw (new Error(`${JSON.stringify(json)}`))
  }
}

export const GetPPID = async (): Promise<Error|Number> => {
  try {
    !ppid && await getPPID()
  } catch (err) {
    return err
  }
  return ppid
}

export async function fetchShopIndex (): Promise<Record<string, any>> {
  try {
    !ppid && await getPPID()
  } catch (err) {
    return err
  }


  const Request: RequestInit = {
    mode: 'cors',
    headers: ajaxHeader
  }
  try {
    const responce = await fetch(`${baseURL}/Shop/index/ppid/${ppid}`, Request)
    return await responce.json()
  } catch (err) {
    return err
  }
}
